<template>
  <div class="px-5 py-4 bg-white">
    <el-row :gutter="0">
      <el-col :span="24" :xs="24">
        <!-- 标题 -->
        <HeadTitle text="用户管理"/>
      </el-col>
      <el-col :span="24" :xs="24">
        <!-- 搜索 -->
        <el-form :model="queryParams" ref="queryRef" :inline="true">
          <el-form-item label="所属科室" prop="deptId">
            <el-select
              v-model="queryParams.deptId"
              placeholder="请选择科室"
              clearable
              style="width: 240px"
              @change="getList"
            >
              <el-option
                v-for="item in deptOption"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户姓名" prop="fullName">
            <el-input
              v-model="queryParams.fullName"
              placeholder="请输入姓名"
              clearable
              @keyup.enter="getList"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="创建时间" style="width: 308px">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="getList"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getList">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery(queryRef)">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <!-- 按钮 -->
    <el-row :gutter="20" justify="space-between">
      <el-col :span="20">
        <el-button type="primary" icon="plus" @click=";(open = true),(isAdd = true), reset()">新增</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-row :gutter="0" class="mt-4">
      <el-col :span="24">
        <Table
          :column="tableColumn"
          :table-data="userList"
          :option="option"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          @command="handleCommand"
        >
          <template #status="scope">
            <el-tag v-if="scope.row.status === '0'" size="mini" type="success">正常</el-tag>
            <el-tag v-if="scope.row.status === '1'" size="mini" type="danger">停用</el-tag>
          </template>
          <template #reset="scope">
            <svg aria-hidden="true" class="ml-4 w-4 h-4" @click="handleResetPwd(scope.row)">
              <use xlink:href="#icon-reset"/>
            </svg>
          </template>
        </Table>
      </el-col>
    </el-row>

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" v-model="open" append-to-body width="500px">
      <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="科室选择" prop="deptId">
          <el-select v-model="form.deptId" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in deptOption"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户姓名" prop="fullName">
          <el-input v-model="form.fullName" placeholder="请输入用户姓名"/>
        </el-form-item>
        <el-form-item label="用户账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户账号" maxlength="20"/>
        </el-form-item>
        <el-form-item v-if="isAdd" label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" type="password" minlength="5" maxlength="20" show-password />
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" active-value="0" inactive-value="1"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(deptRef)">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  addUser,
  delUser,
  getDeptTree,
  getUser,
  listUser,
  resetUserPwd,
  updateUser
} from '@/api/user'
import {ElMessage, ElMessageBox, FormInstance} from 'element-plus'
import {reactive, ref, toRefs} from 'vue'


const deptOption = ref([]) //科室选择
const queryRef = ref()
const dateRange = ref([]) //时间
const title = ref('新增用户')
const open = ref(false)
const isAdd = ref(true)

interface fromType {
  userName: StrUn //用户账号
  fullName: StrUn //用户姓名
  phonenumber: NumUn //手机号
  email: StrUn //邮箱
  status: StrUn //状态
  deptId: NumUn //科室id
  password: StrUn
  userId?: number
}

interface queryType {
  pageNum: number
  pageSize: number
  status: StrUn
  deptId?: NumUn
  fullName?: StrUn
  userName?: StrUn
  startTime?: Date
  endTime?: Date
}

interface dataType {
  form: fromType
  queryParams: queryType
  rules: any
}

const data = reactive<dataType>({
  form: {
    fullName: undefined,
    userName: undefined,
    phonenumber: undefined,
    email: undefined,
    deptId: undefined,
    status: '0',
    password: undefined,
    userId: undefined
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: undefined, //科室名称
    fullName: undefined, //用户姓名
    userName: undefined, //用户账号
    status: undefined, //状态
    startTime: undefined,// 开始时间
    endTime: undefined,// 结束时间
  },
  rules: {
    fullName: [{required: true, message: '用户姓名不能为空', trigger: 'blur'}],
    userName: [
      { required: true, message: '用户账号不能为空', trigger: 'blur' },
      { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' },
      { pattern: /^[a-zA-z]*$/, message: '用户账号仅支持英文', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '用户密码不能为空', trigger: 'blur' },
      { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
    ],
    deptId: [{required: true, message: '科室不能为空', trigger: 'blur'}],
    status: [{required: true}],
    email: [
      {
        pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"]
      }
    ],
    phonenumber: [
      {
        pattern: /^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur"
      }
    ]
  }
})

const {queryParams, form, rules} = toRefs(data)

//表格配置
const tableColumn = [
  {type: 'index', label: '序号', align: 'center', width: '100'},
  {prop: 'userName', label: '用户账号', align: 'center'},
  {prop: 'fullName', label: '用户姓名', align: 'center'},
  {prop: 'deptName', label: '科室', align: 'center'},
  {prop: 'phonenumber', label: '手机号', align: 'center'},
  {prop: 'status', label: '状态', align: 'center', slot: 'status'},
  {prop: 'createTime', label: '创建时间', align: 'center', showOverflowTooltip: true},
  {
    label: '操作',
    align: 'center',
    buttons: [
      {name: '修改', type: 'edit', command: 'edit', link: true, icon: 'Edit'},
      {slot: 'reset'},
      {name: '删除', type: 'delete', command: 'delete', link: true, icon: 'Delete'}
    ]
  }
] as Table.Column[]

interface State {
  userList: Array<object>
  option: Table.Option
}

const state = reactive<State>({
  userList: [],
  option: {
    loading: false,
    showPagination: true,
    height: 580,
    paginationConfig: {
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  }
})
const {userList, option} = toRefs(state)

/** 科室 */
const DeptTree = () => {
  getDeptTree().then((res: any) => {
    deptOption.value = res.data
  })
}

/** 用户列表 */
const getList = () => {
  if (dateRange.value?.length) {
    queryParams.value.startTime = dateRange.value[0] //开始时间
    queryParams.value.endTime = dateRange.value[1] //结束时间
  }
  option.value.loading = true
  listUser(queryParams.value).then((res: any) => {
    userList.value = res.rows
    if (option.value.paginationConfig) {
      option.value.paginationConfig.total = res.total
    }
    option.value.loading = false
  })
}
/** 重置按钮操作 */
const resetQuery = (queryRef: { resetFields: () => void }) => {
  queryRef.resetFields()
  dateRange.value = []
  queryParams.value.startTime = undefined //开始时间
  queryParams.value.endTime = undefined //结束时间
  getList()
}

/** 取消按钮 */
const cancel = (): void => {
  open.value = false
  reset()
}

/** 表单重置 */
const reset = (): void => {
  form.value = {
    fullName: undefined,
    userName: undefined,
    phonenumber: undefined,
    email: undefined,
    deptId: undefined,
    password: undefined,
    status: '0'
  }
}

//操作按钮
const handleCommand = (command: string | number, row?: any) => {
  const userId: number = row?.userId
  const userName: string = row?.userName
  switch (command) {
    //修改
    case 'edit':
      reset()
      getUser(userId).then((res: any) => {
        form.value = res.data
        title.value = '修改用户'
        isAdd.value = false
        open.value = true
      })
      break
    case 'delete':
      //删除
      ElMessageBox.confirm('是否确认删除' + userName + '？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delUser(userId).then(() => {
            getList()
            ElMessage.success('删除成功')
          })
        })
        .catch(() => {
        })
      break
    default:
      break
  }
}

/** 提交按钮 */
const deptRef = ref<FormInstance>()
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (form.value.userId != undefined) {
        updateUser(form.value).then(() => {
          ElMessage.success('修改成功')
          open.value = false
          getList()
        })
      } else {
        addUser(form.value).then(() => {
          ElMessage.success('新增成功')
          open.value = false
          getList()
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

/** 重置密码按钮操作 */
const handleResetPwd = (row: any): void => {
  ElMessageBox.prompt('请输入"' + row.userName + '"的新密码', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    closeOnClickModal: false,
    inputPattern: /^.{5,20}$/,
    inputErrorMessage: '用户密码长度必须介于 5 和 20 之间'
  })
    .then(({value}) => {
      resetUserPwd(row.userName, value).then(() => {
        ElMessage.success('修改成功，新密码是：' + value)
      })
    })
    .catch(() => {
    })
}
/** 分页*/
const handleCurrentChange = (pageNum: number): void => {
  if (option.value.paginationConfig) {
    option.value.paginationConfig.currentPage = pageNum
    queryParams.value.pageNum = pageNum
  }
  getList()
}

/** 分页*/
const handleSizeChange = (pageSize: number): void => {
  if (option.value.paginationConfig) {
    option.value.paginationConfig.pageSize = pageSize
    queryParams.value.pageSize = pageSize
  }
  getList()
}
getList()
DeptTree()
</script>
<style scoped lang="less"></style>
